<template>
	<div>
		<div class="container">
			<div class="container">
				<div class="toolbar mt-2">
					<a-form ref="searchRef" :label-col="{style: { width: '130px' }}" :model="searchState" @finish="current=1;loading=true;initData()">
						<a-row>
							<a-col :span="8">
								<a-form-item label="城市公司/专业公司">
									<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="项目名称">
									<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="选择供应商" name="supplier_id">
									<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择" :options="userList" option-filter-prop="label" allow-clear></a-select>
								</a-form-item>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="8">
								<a-form-item label="物资类型/规格型号" name="model">
									<a-input v-model:value="searchState.model" placeholder="请输入" allow-clear></a-input>
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item label="验收时间范围" name="date_range">
									<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
								</a-form-item>
							</a-col>
							<a-col :span="8">
								<a-form-item>
									<a-space>
										<a-button type="primary" html-type="submit">
											<search-outlined />搜索
										</a-button>
										<a-button type="link" @click="filterTableStats">
											<search-outlined />导出台账
										</a-button>
									</a-space>
								</a-form-item>
							</a-col>
						</a-row>
					</a-form>
				</div>
				<div class="mt-2">
					<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" children-column-name="children" :default-expand-all-rows="false" :data-source="psSource" :pagination="pagination" :loading="loading" @change="initData">
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'operation'">
								<a-space>
									<a-button v-permission="148" type="link" @click="show(record)">
										<right-outlined />查看
									</a-button>
								</a-space>
							</template>
						</template>
					</a-table>
				</div>
			</div>
		</div>
		<a-modal v-model:visible="tableStatsModal.visible" title="导出台账显示" :width="400" :body-style="{overflowY: 'auto'}" @ok="handleExport">
			<a-checkbox-group v-model:value="tableStatsModal.stats">
				<a-row>
					<a-col v-for="(item) in checkColumns" :key="item.key" :span="24">
						<a-checkbox :value="item.value">{{ item.label }}</a-checkbox>
					</a-col>
				</a-row>
			</a-checkbox-group>
		</a-modal>
	</div>
</template>
<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { usePagination } from "vue-request";
import { post, treeToList } from "../utils/index.js";
import dayjs from "dayjs";
import { exportData } from "@/utils/exportData.js";
const userList = ref([]);
const projectOptions = ref([]);
const companyOptions = ref([]);
const gonghaolist = ref([]); //工号列表
const route = useRoute();
const router = useRouter();
const query = route.query;
const searchRef = ref();
const searchState = reactive({});
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));
const tableStatsModal = ref({
	loading: false,
	visible: false,
	stats: [],
})
const yslist = [
	{ value: 0, label: "请选择" },
	{ value: 1, label: "钢筋" },
	{ value: 2, label: "混凝土" },
	{ value: 3, label: "周转材料" },
	{ value: 4, label: "机械" },
	{ value: 5, label: "其它" },
	{ value: 6, label: "辅助材料" }
];

const columns = [
	{
		title: "序号",
		dataIndex: "index",
		key: "index",
		width: 100,
		align: "left",
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: "项目名称",
		dataIndex: "project_name",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return record.supplyOrder?.project?.name;
		}
	},
	{
		title: "验收类型",
		dataIndex: "ys_type",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return yslist.filter(item => item.value === record.supplyOrder.ys_type)[0]?.label;
		}
	},
	{
		title: "验收时间",
		//dataIndex: ["supplyOrder", "deliver_time"],
		dataIndex: "enter_time",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//return dayjs(record.supplyOrder.deliver_time).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "供货单位",
		dataIndex: "supplier_name",
		sorter: false,
		width: 200,
		align: "center"
	},
	{
		title: "材料名称",
		dataIndex: "material_name",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.material.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "model",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.material.model;
		}
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.material.unit;
		}
	},
	{
		title: "采购数量",
		dataIndex: "quantity",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text || record.fangliang;
		}
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		sorter: false,
		width: 150,
		align: "center"
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		sorter: false,
		width: 150,
		align: "center"
	},
	{
		title: "发货单编号",
		dataIndex: "fh_code",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.supplyOrder.code;
		}
	},
	{
		title: "验收单编号",
		dataIndex: "ys_Code",
		sorter: false,
		width: 150,
		align: "center"
	},
	{
		title: "使用部位",
		dataIndex: "use_position",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			let value = "";
			if (record.gonghao_id) {
				value += gonghaolist.value.filter(item => item.value === record.gonghao_id)[0]?.label || "";
			}
			if (record.fangliang) {
				value += gonghaolist.value.filter(item => item.value === record.position)[0]?.label || "";
			}
			return value;
		}
	},
	{
		title: "技术指标",
		dataIndex: "art_indexes",
		sorter: false,
		width: 150,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		sorter: false,
		width: 150,
		align: "center"
	},
	{
		title: "操作",
		dataIndex: "operation",
		width: 80,
		sorter: false,
		align: "center"
	}
];
const innerColumns = computed(() => {
	const columnList = []
	columns.map((i, index) => {
		if (i.dataIndex !== "operation") {
			columnList.push(i)
		}
	})
	return columnList;
});
const checkColumns = computed(() => {
	return innerColumns.value.map(item => {
		return { value: item.dataIndex, label: item.title }
	})
})
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24])
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
post("department/projects", { type: 4 }).then(({ data }) => {
	gonghaolist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("user", { is_supplier: 1, page_size: 1000 }).then(({ data }) => {
	userList.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name || d.mobile
		};
	});
});

const { data, loading, run, current, pageSize, total } = usePagination(async params => {
	const search = { ys_status: 2 };
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		search.project_ids = projectOptions.value
			.filter(item => {
				return item.parseIds.includes(searchState.company_id);
			})
			.map(item => item.value)
			.join(",");
		// if (!search.project_ids) {
		// 	return [];
		// }
	}
	return post("supplyOrder/bySupplier", { ...params, ...searchState, ...search });
},
{
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
}
);
const psSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		d.art_indexes = d.art_indexes ? JSON.parse(d.art_indexes).map(item => item.gonghao_name).join(',') : "";
		return d;
	})
);
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters,
		start_time: searchState.date_range && searchState.date_range[0],
		end_time: searchState.date_range && searchState.date_range[1],
	}})
	// if (filters.date_range) {
	// 	filters.start_time = filters.date_range[0];
	// 	filters.end_time = filters.date_range[1];
	// } else {
	// 	filters.start_time = null;
	// 	filters.end_time = null;
	// }
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};

if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.supplier_id) searchState.supplier_id = parseInt(query.supplier_id);
	if (query.model) searchState.model = query.model;
	if (query.start_time && query.end_time) {
		searchState.date_range = [
			dayjs(query.start_time).format('YYYY-MM-DD HH:mm:ss'),
			dayjs(query.end_time).format('YYYY-MM-DD HH:mm:ss')
		];
	}
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const show = record => {
	// const id = record.supplier_id;
	// router.push(`/yanshou/standingBook/info/${id}`);
	router.push(`/yanshoulog/info/${record.supplyOrder?.id}?code=${record.ys_Code}&toPath=1`);
};
// 打开导出弹窗
const filterTableStats = () => {
	tableStatsModal.value.stats = []
	tableStatsModal.value.visible = true;
	columns.map((i) => {
		if (i.dataIndex !== "operation") {
			tableStatsModal.value.stats.push(i.dataIndex)
		}
	})
	
}
const handleExport = async () => {
	tableStatsModal.value.visible = false;
	const search = {};
	if (searchState.company_id) {
		search.project_ids = projectOptions.value
			.filter(item => {
				return item.parseIds.includes(searchState.company_id);
			})
			.map(item => item.value)
			.join(",");
		if (!search.project_ids) {
			return [];
		}
	}
	const dates = await post("supplyOrder/bySupplier", {
		keys: tableStatsModal.value.stats.join(','),
		page: 1,
		page_size: 10000,
		submit: "export",
		...searchState,
		...search,
		ys_status: 2
	});
	if (dates.url) window.location.href = dates.url;
	// const result = [];
	// for (let i = 0; i < dates.data.length; i++) {
	// 	const data = dates.data[i];
	// 	const d = {};
	// 	for (const column of columns) {
	// 		if (column.customRender) {
	// 			d[column.dataIndex] = column.customRender({
	// 				text: data[column.dataIndex],
	// 				record: data,
	// 				index: i
	// 			});
	// 		} else {
	// 			d[column.dataIndex] = data[column.dataIndex];
	// 		}
	// 	}
	// 	result.push(d);
	// }
	// exportData(columns, result, `验收台账.xlsx`);
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
